import {createStore}  from 'redux';
import {persistStore, persistReducer} from 'redux-persist';
import storageSession from 'redux-persist/lib/storage/session';

// 1. 定义初始状态
let initState = {
    count: 10,
    token: '',
    phone: ''
} 

// 2. 定义action creator用来创建一个action
export const updateCount = (payload)=> {
    // 返回一个action
    return {
        type: 'UPDATE-COUNT',
        payload
    }
}
export const updateToken = (payload)=> {
    // 返回一个action
    return {
        type: 'UPDATE-TOKEN',
        payload
    }
}
export const updatePhone = (payload)=> {
    // 返回一个action
    return {
        type: 'UPDATE-PHONE',
        payload
    }
}

// 3. 定义reducer,用来修改状态
const reducer = (state=initState,action)=> {
    let {type,payload} = action;
    switch(type) {
        case 'UPDATE-TOKEN':
            return {
                ...state,
                token: payload
            }
        case 'UPDATE-COUNT':
            return {
                ...state,
                count: state.count+payload
            }
        case 'UPDATE-PHONE':
            return {
                ...state,
                phone: payload 
            }
        default:
            return state;
    } 
}
 

// 持久化配置
const storageConfig = {
    key: 'root', // 必须有的
    storage:storageSession, // 缓存机制
    blacklist: [] // reducer 里不持久化的数据,除此外均为持久化数据
}
const newReducer = persistReducer(storageConfig, reducer);
export let store = createStore(newReducer);
export let newStore = persistStore(store); 

